package 链表.单向.练习;

public class Text_2 {
    public static ListNode head;
    public void addFirst(int data){
        //代码不能交换
        //必须先绑定信息
        ListNode listNode = new ListNode(data);
        listNode.next = head;
        head = listNode;
    }
    void display(){
        ListNode cur = head;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur = cur.next;//cur向后走一步
        }
        System.out.println();
    }
    int  size(Text_2 list){
        int count = 0;
        ListNode cur = head;
        while (cur!=null){
            cur = cur.next;
            count++;
        }
        return count;
    }
    ListNode findListNode(Text_2 list){
        ListNode mid = head;
        if(head == null){
            return null;
        }
        if(head.next ==null){
            return head;
        }
        int count = size(list);
        int midCount = count/2;
        while (midCount>0){
            mid = mid.next;
            midCount--;
        }
        return mid;
    }
    ListNode findListNode1(){
        //使用快慢双指针，快的是慢的二倍；那么快的到了，慢的一定就在中间
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null&&fast.next!=null){//不能交换
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        Text_2 text2 = new Text_2();
        text2.addFirst(1);
        text2.addFirst(2);
        text2.addFirst(3);
        ListNode mid = text2.findListNode(text2);
        System.out.println(mid.val);
        ListNode mid1 = text2.findListNode1();
        System.out.println(mid1.val);

    }

}
